﻿using Common;
using Service.DtoModel;
using Service.DtoModel.DeskApp;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Threading.Tasks;

namespace Service.Implements
{
    public class MenuService : BaseServer<Menu>
    {
        /// <summary>
        /// 获取所有菜单
        /// </summary>
        /// <param name="parms"></param>
        /// <returns></returns>
        public async Task<ApiResult<List<Menu>>> QueryMenusList(ParmString parms)
        {
            var res = new ApiResult<List<Menu>>() { statusCode = (int)ApiEnum.Error };
            try
            {
                DataTable _TB = null;
                var sql = new StringBuilder(" select * from menus ");
                if (!string.IsNullOrEmpty(parms.parm))
                {
                    var _parms = new List<SugarParameter>() { new SugarParameter("@msName", parms.parm) };
                    sql.Append(" where msName=@msName ");
                    _TB = Db.Ado.GetDataTable(sql.ToString(), _parms);
                }
                else
                {
                    _TB = Db.Ado.GetDataTable(sql.ToString());
                }
                List<Menu> _datas = new ModelHandler<Menu>().FillModel(_TB);
                res.data = _datas;
                res.statusCode = (int)ApiEnum.Status;
            }
            catch (Exception ex)
            {
                res.message = ex.Message;
                res.success = false;
                Logger.Default.ProcessError((int)ApiEnum.Error, ex.Message);
            }
            return res;
        }

        /// <summary>
        /// 根据商品类型编号获取商品
        /// </summary>
        /// <param name="parms"></param>
        /// <returns></returns>
        public async Task<ApiResult<List<MenusDto>>> QueryMenusByMtId(ParmString parms)
        {
            var res = new ApiResult<List<MenusDto>>() { statusCode = (int)ApiEnum.Error };
            try
            {
                DataTable _TB = null;
                var sql = new StringBuilder("SELECT a.*,  b.typeName mtName FROM menus a LEFT JOIN sys_type b ON a.mtId=b.typeId and b.typeGroup = 2 ");
                if (!string.IsNullOrEmpty(parms.parm))
                {
                    var _protypeid = 0;
                    int.TryParse(parms.parm, out _protypeid);
                    var _parms = new List<SugarParameter>() { new SugarParameter("@mtId", _protypeid) };
                    sql.Append("where a.mtId=@mtId ");
                    _TB = Db.Ado.GetDataTable(sql.ToString(), _parms);
                }
                else
                {
                    _TB = Db.Ado.GetDataTable(sql.ToString());
                }
                List<MenusDto> _datas = new List<MenusDto>();
                if (_TB != null)
                {
                    var _rowLen = _TB.Rows.Count;
                    for (int i = 0; i < _rowLen; i++)
                    {
                        var _msId = 0; if (_TB.Rows[i]["msId"] != null && _TB.Rows[i]["msId"] != DBNull.Value) int.TryParse(_TB.Rows[i]["msId"].ToString(), out _msId);
                        var _mtId = 0; if (_TB.Rows[i]["mtId"] != null && _TB.Rows[i]["mtId"] != DBNull.Value) int.TryParse(_TB.Rows[i]["mtId"].ToString(), out _mtId);
                        var _stId = 0; if (_TB.Rows[i]["stId"] != null && _TB.Rows[i]["stId"] != DBNull.Value) int.TryParse(_TB.Rows[i]["stId"].ToString(), out _stId);
                        var _msScalar = 0; if (_TB.Rows[i]["msScalar"] != null && _TB.Rows[i]["msScalar"] != DBNull.Value) int.TryParse(_TB.Rows[i]["msScalar"].ToString(), out _msScalar);
                        var _msPrice = 0.0; if (_TB.Rows[i]["msPrice"] != null && _TB.Rows[i]["msPrice"] != DBNull.Value) double.TryParse(_TB.Rows[i]["msPrice"].ToString(), out _msPrice);
                        var _msCost = 0.0; if (_TB.Rows[i]["msCost"] != null && _TB.Rows[i]["msCost"] != DBNull.Value) double.TryParse(_TB.Rows[i]["msCost"].ToString(), out _msCost);
                        var _msMoney = 0.0; if (_TB.Rows[i]["msMoney"] != null && _TB.Rows[i]["msMoney"] != DBNull.Value) double.TryParse(_TB.Rows[i]["msMoney"].ToString(), out _msMoney);
                        var _proImg = ConfigExtensions.Configuration["GroupInfo:defaultProImg"];
                        if (_TB.Rows[i]["proImg"] != null && _TB.Rows[i]["proImg"] != DBNull.Value)
                        {
                            var _proCurImg = _TB.Rows[i]["proImg"].ToString();
                            if (FileHelper.IsExistFile(_proCurImg)) _proImg = _proCurImg;
                        }
                        var _curObj = new MenusDto
                        {
                            msId = _msId,
                            mtId = _mtId,
                            msPrice = _msPrice,
                            msScalar = _msScalar,
                            msCost = _msCost,
                            msMoney = _msMoney,
                            stId = _stId,
                            proImg = _proImg,
                            msAmount = 0,
                            mtName = _TB.Rows[i]["mtName"].ToString(),
                            msUnit = _TB.Rows[i]["msUnit"].ToString(),
                            msName = _TB.Rows[i]["msName"].ToString(),
                            msSpell = _TB.Rows[i]["msSpell"].ToString()
                        };
                        _datas.Add(_curObj);
                    }
                }
                res.data = _datas;
                res.statusCode = (int)ApiEnum.Status;
            }
            catch (Exception ex)
            {
                res.message = ex.Message;
                res.success = false;
                Logger.Default.ProcessError((int)ApiEnum.Error, ex.Message);
            }
            return res;
        }

        /// <summary>
        /// 获取分页数据
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        public async Task<ApiResult<Page<Menu>>> GetPagesAsync(PageParm parm)
        {
            var res = new ApiResult<Page<Menu>>();
            try
            {
                res.data = await Db.Queryable<Menu>()
                                   .WhereIF(!string.IsNullOrEmpty(parm.key), m => m.msName.Contains(parm.key))
                                   .WhereIF(parm.types > 0, m => m.mtId == parm.types)
                                   .OrderBy(m => m.createDate, OrderByType.Desc)
                                   .ToPageAsync(parm.page, parm.limit);
                res.statusCode = (int)ApiEnum.Status;
            }
            catch (Exception ex)
            {
                res.statusCode = (int)ApiEnum.Error;
                Logger.Default.ProcessError((int)ApiEnum.Error, ex.Message);
            }
            return res;
        }

        /// <summary>
        /// 根据主键删除数据
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        public async Task<ApiResult<string>> DeleteAsync(string parm)
        {
            var list = Utils.StrToListString(parm);
            var isok = await Db.Deleteable<Menu>().Where(m => list.Contains(m.msId.ToString())).ExecuteCommandAsync();
            var res = new ApiResult<string>
            {
                success = isok > 0,
                statusCode = isok > 0 ? (int)ApiEnum.Status : (int)ApiEnum.Error,
                data = isok > 0 ? "1" : "0"
            };
            return res;
        }

        /// <summary>
        /// 更新库存
        /// </summary>
        /// <param name="datas"></param>
        /// <returns></returns>
        public async Task<ApiResult<string>> UpProStock(List<MenusDto> datas)
        {
            var res = new ApiResult<string> { statusCode = (int)ApiEnum.Error };
            try
            {
                Db.Ado.BeginTran();
                var isUp = string.Empty;
                foreach (var item in datas)
                {
                    var _isUp = Db.Updateable<Menu>()
                              .SetColumns(it => it.msScalar == item.msScalar)
                              .Where(it => it.msId == item.msId)
                              .ExecuteCommand();
                    isUp += _isUp > 0 ? "true" : "false";
                }
                if (isUp.IndexOf("false") < 0) res.statusCode = (int)ApiEnum.Status;
                Db.Ado.CommitTran();
            }
            catch (Exception ex)
            {
                Db.Ado.RollbackTran();
                Logger.Default.Debug("更新产品库存异常", ex);
            }
            return res;
        }
    }
}
